/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.opprua.tidy.gens;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.opprua.tidy.util.CodePrint;

/**
 * TODO: add Java doc
 *
 * Prepared for first commit: 15.04.2007
 *
 * @author Lin Li
 */
public class GTry extends Gtor {

	private static class Ex {
		public String type;
		public String name;
		public GState statements;

		public Ex(String t, String n) {
			type = t;
			name = n;
			statements = new GState();
		}
	}

	private GState statements;
	private List<Ex> catches = new ArrayList<Ex>();
  
  /**
   * <p>Constructor for a try/catch block.</p>
   */
	public GTry() {
		statements = new GState();
	}

	/**
	 * <p>Add a statement in the try block</p>
   * 
	 * @param statement The statement to add
   * @return this, for chained calls
	 */
	public GTry addWorkStatement(GState statement) {
		statements.addStatement(statement);
		return this;
	}

  /**
   * <p>Add a statement in the try block</p>
   * 
   * @param statement The statement to add
   * @return this, for chained calls
   */
	public GTry addWorkStatement(String statement) {
		statements.addStatement(statement);
		return this;
	}
  
  /**
   * <p>Add a catch block. The statement returned is used to add statements
   * inside the block.</p>
   * 
   * @param type the class name for the exception
   * @param name the variable name for the exception
   * @return the statement inside the catch block, empty in the beginning
   */
	public GState newProcessing(String type, String name) {
		Ex ex = new Ex(type, name);
		catches.add(ex);
		return ex.statements;
	}

	/**
	 * @see Gtor#dump(CodePrint w)
	 */
	public void dump(CodePrint w) {

		blockComments(w);

		w.print("try ");
		statements.dump(w);
		for (Iterator<Ex> iter = catches.iterator(); iter.hasNext();) {
			Ex element = iter.next();

			w.print(" catch (" + element.type + " " + element.name + ") ");
			element.statements.dump(w);
		}
	}
}
